#!/usr/bin/env bash
# Summary: Display prefix for a Node version
# Usage: nodenv prefix [<version>]
#
# Displays the directory where a Node version is installed. If no
# version is given, `nodenv prefix' displays the location of the
# currently selected version.

set -e
[ -n "$NODENV_DEBUG" ] && set -x

# Provide nodenv completions
if [ "$1" = "--complete" ]; then
  echo system
  exec nodenv-versions --bare
fi

if [ -n "$1" ]; then
  export NODENV_VERSION="$1"
elif [ -z "$NODENV_VERSION" ]; then
  NODENV_VERSION="$(nodenv-version-name)"
fi

if [ "$NODENV_VERSION" = "system" ]; then
  if NODE_PATH="$(nodenv-which node)"; then
    NODE_PATH="${NODE_PATH%/*}"
    NODENV_PREFIX_PATH="${NODE_PATH%/bin}"
    echo "${NODENV_PREFIX_PATH:-/}"
    exit
  else
    echo "nodenv: system version not found in PATH" >&2
    exit 1
  fi
fi

NODENV_PREFIX_PATH="${NODENV_ROOT}/versions/${NODENV_VERSION}"
if [ ! -d "$NODENV_PREFIX_PATH" ]; then
  echo "nodenv: version \`${NODENV_VERSION}' not installed" >&2
  exit 1
fi

echo "$NODENV_PREFIX_PATH"
